#ifdef CHANGED
#include "copyright.h"
#include "system.h"
#include "synchconsole.h"
#include "synch.h"
static Semaphore *readAvail;
static Semaphore *writeDone;
static Semaphore *putNotBusy;
static Semaphore *getNotBusy;
static void ReadAvail(int arg) { readAvail->V(); }
static void WriteDone(int arg) { writeDone->V(); }
SynchConsole::SynchConsole(char *readFile, char *writeFile)
{
  readAvail = new Semaphore("read avail", 0);
  writeDone = new Semaphore("write done", 0);
  putNotBusy = new Semaphore("Put not busy", 1);
  getNotBusy = new Semaphore("Get not busy", 1);
  console = new Console(readFile, writeFile, ReadAvail, WriteDone, 0);
}
SynchConsole::~SynchConsole()
{
  delete console;
  delete writeDone;
  delete readAvail;
  delete putNotBusy;
  delete getNotBusy;
}
void SynchConsole::SynchPutChar(const char ch)
{
	putNotBusy->P();
  	console->PutChar(ch);
  	writeDone->P();
  	putNotBusy->V();
}
char SynchConsole::SynchGetChar()
{
	getNotBusy->P();
	readAvail->P();
	char ch = console->GetChar();
	getNotBusy->V();
   	return ch;
   	
}
void SynchConsole::SynchPutString(const char s[])
{
	putNotBusy->P();
	int i = 0;
	if (s != NULL) {
		while ( s[i] != EOF && s[i] != '\0'){
			console->PutChar(s[i]);
			writeDone->P();
			i++;
		}
		
//		console->PutChar('\n');
//		writeDone->P();
		
		//writeDone->V();
	}
	
	putNotBusy->V();
	

}

/**
 * SynchGetString lit au plus size-1 caracteres depuis stream et les
 * place dans le tampon pointe par s.
 * La lecture s'arrete apres un EOF ou un retour-chariot.
 * Si un retour chariot (newline) est lu, il est place dans dans le tampon.
 * Un caractere nul \0 est place a la fin de la ligne.
 * */
void SynchConsole::SynchGetString(char *s, int n)
{
	getNotBusy->P();
	int i = 0;
	readAvail->P();
	char c = console->GetChar();
	s[i] = c;
	i++;
	//console->PutChar(c);
	//writeDone->P();
  	while (i < (n-1) && c != '\0' && c != '\n' && c != EOF)  {
  		readAvail->P();
  		c = console->GetChar();
  		//console->PutChar(c);
  		//writeDone->P();
  		if (c !=  '\0' && c != '\n' && c != EOF) {
  			s[i] = c;
  			i++;
  		}
	}
  	//console->PutChar('w');
  	//writeDone->P();
	s[i] = '\0';
	
	getNotBusy->V();
}

void SynchConsole::SynchPutInt(int entier)
{
	
	char chaine[16];
	snprintf(chaine, 16, "%d", entier);
	synchconsole->SynchPutString(chaine); // WriteDone & notBusy by PutString
	
}

void SynchConsole::SynchGetInt(int *entier)
{
	  char chaine[16];
	  synchconsole->SynchGetString(chaine,16);
	  sscanf(chaine,"%d",entier);	
	
}
#endif // CHANGED
